import {Base64} from "js-base64";
import {ElMessage} from "element-plus";

export function useWebSocket(url, onMessage){
    let webSocketInstance
    let webSocketLink = url || import.meta.env.VITE_WEB_SOCKET_URL || '10.255.1.35:8199'
    const timeout = 5 * 1000 // 每5s向服务端发送一次消息
    const serverTimeout = 10 * 1000 // 10s收不到服务端消息算超时
    let timer =  null
    let serverTimer = null
    console.log("websocketUrl",webSocketLink);
    if ("WebSocket" in window) {
        webSocketInstance = new WebSocket(webSocketLink);
    } else if ("MozWebSocket" in window) {
        webSocketInstance = new MozWebSocket(webSocketLink);
    }
    webSocketInstance.onopen = (e) => {
        start();// 启动心跳检测
    };
    // 接收消息
    webSocketInstance.onmessage = (e) => {
        start();// 启动心跳检测
        const {code,data,message} = JSON.parse(window.atob(e.data))
        if (code !== '201') {
            if (code === '400') {
                ElMessage.error(message);
            }else {
                onMessage(code,data,message)
            }
        }
    };
    webSocketInstance.onerror = (e) => {
        console.log("出现错误");
        reset();// 启动心跳检测
    };
    webSocketInstance.onclose = (e) => {
        console.log("连接关闭");
        reset();// 启动心跳检测
    };
    function reset() { // 心跳检测重置
        clearTimeout(timer);
        clearTimeout(serverTimer);
        timer = null;
        serverTimer = null;
        return this;
    }
    function start() { // 心跳检测启动
        reset();
        timer = setTimeout(() => {
            const data = {
                code: "201",
                message: "heartCheck",
                data: null
            }
            webSocketInstance.send(Base64.encode(JSON.stringify(data))); // 定时向服务端发送消息
            if (!serverTimer) {
                serverTimer = setTimeout(() => {
                    // 关闭连接触发重连
                    console.log(new Date().toLocaleString(), "not received pong, close the websocket");
                    webSocketInstance.close(); //关闭websocket或根据业务需求去重连
                }, serverTimeout);
            }
        }, timeout);
    }

    return {
        webSocketInstance
    }
}
